<template>
  <div id="container">
    <div id="my-panel" class="my-panel"></div>
  </div>

  <!-- 
    npm i @amap/amap-jsapi-loader --save ,下载amap的loader
    淘宝镜像
    https://blog.csdn.net/m0_71645665/article/details/135972210
   -->
</template>
  <script>
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  securityJsCode: "982bc10ce0ec45c55d2316dcab389d4e",
};
export default {
  data() {
    return {
      map: null,
      autoOptions: {
        input: "",
      },
      auto: null,
      placeSearch: null,
      searchPlaceInput: "",
      district: null,
      polygons: [],
      isShowHeatMap: false,
      heatmap: null,
      heatmapList: [],
      geolocation: null,
      marker: null,
      driving: null,
    };
  },
  created() {
    this.$bus.$on("serachInput", (value) => {
      this.autoOptions.input = value.searchId;
      this.searchPlaceInput = value.inputValue;
    });
    this.$bus.$on("isShowHeatMap", (value) => {
      this.isShowHeatMap = value;
      console.log(this.isShowHeatMap);
    });
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      AMapLoader.load({
        key: "c8785d0414ff67c7af9e4d1257ec5ad8", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.ToolBar",
          "AMap.Scale",
          "AMap.HawkEye",
          "AMap.MapType",
          "AMap.Geolocation",
          "AMap.AutoComplete",
          "AMap.PlaceSearch",
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 10, //初始化地图级别
            center: [115.26158799145506, 31.656972368288717], //初始化地图中心点位置
          });
          this.map.addControl(new AMap.Scale());
          this.map.addControl(new AMap.ToolBar());
          this.map.addControl(new AMap.HawkEye());
          this.map.addControl(new AMap.MapType());
          this.map.addControl(new AMap.Geolocation());
          this.auto = new AMap.AutoComplete(this.autoOptions);
          this.placeSearch = new AMap.PlaceSearch({
            map: this.map,
          }); //构造地点查询类
          this.auto.on("select", this.select);
          this.geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, // 是否使用高精度定位，默认：true
            timeout: 10000, // 设置定位超时时间，默认：无穷大
            offset: [10, 20], // 定位按钮的停靠位置的偏移量
            zoomToAccuracy: true, //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            position: "RB", //  定位按钮的排放位置,  RB表示右下
          });
          this.addMarker();
          this.addDriving();
          this.geolocation.getCurrentPosition((status, result) => {
            if (status == "complete") {
              this.onComplete(result);
            } else {
              this.onError(result);
            }
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    onComplete(data) {
      console.log(data);
    },
    onError(data) {
      console.log(data);
    },
    // 添加点标记
    addMarker() {
      //添加点标记
      const content = `<div class="custom-content-marker">
        <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png">
        </div>`;
      this.map.plugin("AMap.Marker", () => {
        this.marker = new AMap.Marker({
          content: content, //自定义点标记覆盖物内容
          position: new AMap.LngLat(115.26158799145506, 31.656972368288717), //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          title: "宇宙中心",
        });
        this.map.add(this.marker);
      });
    },
    // 路线规划
    addDriving() {
      const points = [
        { keyword: "北京市", city: "北京" }, //起始点坐标
        { keyword: "商城县", city: "信阳" }, //终点坐标
      ];
      this.map.plugin("AMap.Driving", () => {
        this.driving = new AMap.Driving({
          map: this.map,
          panel: "my-panel",
        });
        //获取起终点规划线路
        this.driving.search(points, (status, result) => {
          if (status === "complete") {
            //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
            //查询成功时，result 即为对应的驾车导航信息
            console.log(result);
          } else {
            console.log("获取驾车数据失败：" + result);
          }
        });
      });
    },
    select(e) {
      this.placeSearch.setCity(e.poi.adcode);
      this.placeSearch.search(e.poi.name); //关键字查询查询
      this.map.setCenter([e.poi.location.lng, e.poi.location.lat]);
      this.map.setZoom(16, true, 1);
      this.drawBounds(e.poi.name);
    },
    // 行政区区域划分
    drawBounds(newValue) {
      //加载行政区划插件
      if (!this.district) {
        //实例化DistrictSearch
        var opts = {
          subdistrict: 0, //获取边界不需要返回下级行政区
          extensions: "all", //返回行政区边界坐标组等具体信息
          level: "district", //查询行政级别为 市
        };

        this.map.plugin(["AMap.DistrictSearch"], () => {
          this.district = new AMap.DistrictSearch(opts);
        });
        // this.district = new AMap.DistrictSearch(opts)
      }
      //行政区查询
      this.district.search(newValue, (status, result) => {
        if (this.polygons != null) {
          this.map.remove(this.polygons); //清除上次结果
          this.polygons = [];
        }
        var bounds = result.districtList[0].boundaries;
        if (bounds) {
          for (var i = 0, l = bounds.length; i < l; i++) {
            //生成行政区划polygon
            var polygon = new AMap.Polygon({
              strokeWeight: 1,
              path: bounds[i],
              fillOpacity: 0.4,
              fillColor: "#80d8ff",
              strokeColor: "#0091ea",
            });
            this.polygons.push(polygon);
          }
        }
        this.map.add(this.polygons);
        this.map.setFitView(this.polygons); //视口自适应
      });
    },
    searchhotchartpos(val) {
      this.map.plugin(["AMap.PlaceSearch"], () => {
        //构造地点查询类
        var placeSearch = new AMap.PlaceSearch({
          pageSize: 50, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: this.searchPlaceInput, // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          //map: this.map, // 展现结果的地图实例
          // panel: 'panel', // 结果列表将在此容器中进行展示。
          // autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        //关键字查询
        placeSearch.search(val, (status, result) => {
          this.getHotChartPos(val, result);
        });
      });
      this.$notify({
        title: "成功",
        message: "热力图获取成果，但是由于电脑性能，我们仅加载部分数据",
        type: "success",
      });
    },
    getHotChartPos(detail, result) {
      let lengthSize = result.poiList.pageSize;
      const count = result.poiList.count;
      // const lengthPage = count / lengthSize
      if (lengthSize > count) {
        lengthSize = count;
      }
      for (var n = 0; n < 2; n++) {
        // this.map.plugin(['AMap.PlaceSearch'], () => {
        //构造地点查询类
        var realSearch = new AMap.PlaceSearch({
          pageSize: 50, // 单页显示结果条数
          pageIndex: n + 1, // 页码
          city: this.searchPlaceInput, // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          // map: this.map, // 展现结果的地图实例
          // panel: 'panel', // 结果列表将在此容器中进行展示。
          // autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        realSearch.search(detail, (status, result) => {
          // for (var j = 0; j < 50; j++) {
          // this.map.remove(this.map.getAllOverlays('marker'))
          //var centerPoint = [result.poiList.pois[j].location.lng, result.poiList.pois[j].location.lat]
          // console.log(result)
          //热力图
          this.showHatChart(result);
          // }
        });
      }
    },
    showHatChart(result) {
      var info = [];
      for (let i = 0; i < 5; i++) {
        info.push({
          lng: result.poiList.pois[i].location.lng,
          lat: result.poiList.pois[i].location.lat,
          count: 3 * 6.4 * Math.round(Math.random() * (10 - 2) + 2),
        });
      }

      this.map.plugin(["AMap.HeatMap"], () => {
        // console.log('nn')
        //初始化heatmap对象
        this.heatmap = new AMap.HeatMap(this.map, {
          radius: 56, //给定半径
          opacity: [0, 0.5],
          /*,
            gradient:{
                0.5: 'blue',
                0.65: 'rgb(117,211,248)',
                0.7: 'rgb(0, 255, 0)',
                0.9: '#ffea00',
                1.0: 'red'
            }
             */
        });
        //设置数据集
        this.heatmap.setDataSet({
          data: info,
          max: 100,
        });
        this.heatmapList.push(this.heatmap);
        this.heatmap.show();
      });
    },
  },
  watch: {
    searchPlaceInput(newValue) {
      if (newValue != null) {
        this.placeSearch.search(newValue);
        this.map.setZoom(16, true, 1);
        this.drawBounds(newValue);
      }
    },
    isShowHeatMap(newValue) {
      if (newValue) {
        this.searchhotchartpos("商场");
      } else {
        this.heatmap.hide();
      }
    },
  },
};
</script>
  
<style lang="scss" scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 100%;
  .my-panel {
    border: 1px red solid;
    position: absolute;
    right: 0px;
    width: 300px;
    height: 400px;
    overflow: auto;
    z-index: 999;
  }
}
</style>
  